package crypt

import (
	"encoding/base64"
	"strings"
)

// 将字符串编码为 Base64
func Base64Encode(str string) string {
	return base64.StdEncoding.EncodeToString([]byte(str))
}

// 将 Base64 编码转换为 URL Safe Base64 编码
func Base64EncodeWithUrlSafe(str string) string {
	base64Str := Base64Encode(str)
	return strings.TrimRight(
		strings.ReplaceAll(strings.ReplaceAll(base64Str, "+", "-"), "/", "_"),
		"=",
	)

}

// 将 URL Safe Base64 编码转换为标准 Base64 编码
func Base64DecodeWithUrlSafe(urlSafeBase64Str string) (string, error) {
	base64Str := strings.ReplaceAll(strings.ReplaceAll(urlSafeBase64Str, "-", "+"), "_", "/")
	for len(base64Str)%4 != 0 {
		base64Str += "="
	}
	return Base64Decode(base64Str)
}

// 将 Base64 解码为字符串
func Base64Decode(base64Str string) (string, error) {
	decodedBytes, err := base64.StdEncoding.DecodeString(base64Str)
	if err != nil {
		return "", err
	}
	return string(decodedBytes), nil
}

// func Base64Encode(input string) string {
// 	return base64.StdEncoding.EncodeToString([]byte(input))
// }

// func Base64Decode(input string) (string, error) {
// 	decodedBytes, err := base64.StdEncoding.DecodeString(input)
// 	if err != nil {
// 		return "", err
// 	}
// 	return string(decodedBytes), nil
// }
